package com.leyou.trade.service.impl;

import com.leyou.common.exception.LyException;
import com.leyou.trade.entity.Order;
import com.leyou.trade.service.OrderService;
import com.leyou.trade.service.PayService;
import com.leyou.trade.utils.PayHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private OrderService orderService;

    @Autowired
    private PayHelper payHelper;

    @Override
    public String getPayUrl(Long orderId) {
        Order order = orderService.getById(orderId);
        String payUrl = payHelper.getPayUrl(orderId, 1L/*order.getActualFee()*/, "付款信息");
        return payUrl;
    }

    @Override
    public void handlerNotify(Map<String, String> notifyParam) {

        payHelper.checkResultCode(notifyParam);
        payHelper.checkReturnCode(notifyParam);
        payHelper.checkResponseSignature(notifyParam);

        String out_trade_no = notifyParam.get("out_trade_no");
        String total_fee = notifyParam.get("total_fee");

        if(StringUtils.isEmpty(out_trade_no) || StringUtils.isEmpty(total_fee)){
            throw new LyException(400,"支付信息有误，已转人工处理，请稍后");
        }

        Long orderId = Long.valueOf(out_trade_no);
        Order order = this.orderService.getById(orderId);

        if(order.getStatus()==1){

            if(Long.valueOf(total_fee).longValue() != 1L/*order.getActualFee().longValue()*/){
                throw new LyException(400,"支付信息有误，已转人工处理，请稍后");
            }

            this.orderService.update()
                    .set("status",2)
                    .set("pay_time",new Date())
                    .eq("order_id",orderId)
                    .eq("status",1)
                    .update();
        }
    }
}
